package com.czxy.controller;

import com.czxy.config.JwtProperties;
import com.czxy.pojo.User;
import com.czxy.rpvo.LoginResponse;
import com.czxy.service.AuthService;
import com.czxy.util.JwtUtils;
import com.czxy.vo.BaseResult;
import com.czxy.vo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.PrivateKey;

/**
 * @author 张青卯
 * @date Created in 10:49 2019/2/26
 */
@RestController
@RequestMapping
public class AuthController {

    private final AuthService authService;

    private final JwtProperties jwtProperties;

    @Autowired
    public AuthController(AuthService authService, JwtProperties jwtProperties) {
        this.authService = authService;
        this.jwtProperties = jwtProperties;
    }

    @PostMapping("login")
    public ResponseEntity<Object> login(@RequestBody User user){
        User userByMobile = this.authService.findUserByMobile(user);
        int i = -100;
        if (userByMobile == null || userByMobile.getId()==i){
            BaseResult result = new BaseResult(1,"未找到用户信息");
            return ResponseEntity.ok(result);
        }
        UserInfo userInfo = new UserInfo(user.getId(),user.getSite());
        PrivateKey key = jwtProperties.getPrivateKey();
        String token = null;
        try {
            token = JwtUtils.generateToken(userInfo,key,30);
        } catch (Exception e){
            e.printStackTrace();
        }
        LoginResponse response = new LoginResponse(1, "成功响应用户数据", userByMobile, token);
        return ResponseEntity.ok(response);
    }
}
